﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using DP.Data.OleDb;
using System.Web.UI;
using System.Web;
using System.Configuration;

namespace CRM.BLL
{
    [Serializable] 
    public class OleDbExcel
    {

        public static string GetFileName(Page page)
        {
            return page.Server.MapPath("~/TempFilePath/Temp").TrimEnd('\\') + "\\" + "temp.xls";
        }

        /// <summary>
        /// Datas the table to excel.
        /// </summary>
        /// <param name="dt">The dt.</param>
        /// <param name="dicts">The dicts.</param>
        /// <param name="fileName">Name of the file.</param>
        public static void DataTableToExcel(DataTable dt, Dictionary<string, string> dicts, string fileName)
        {
            Page page = HttpContext.Current.Handler as Page;
            if (page == null) return;
            string oledbConn = ConfigurationManager.ConnectionStrings["OleDb4"].ConnectionString.ToString();
            DP.Data.OleDb.OleDbHelper oleDbHelper = new OleDbHelper(String.Format(oledbConn, GetFileName(page)));

            string tableName = "";

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //创建sheet
                if (i%65535 == 0)
                {
                    tableName = string.Format("{0}Page{1}", dt.TableName, (i/65535) + 1);
                    string createTable = CreateSheetSQL(dt, dicts, tableName);
                    oleDbHelper.ExecuteNonQuery(CommandType.Text, createTable, null);
                }

                #region 插入语句

                oleDbHelper.ExecuteNonQuery(CommandType.Text, InsertDataSQL(dt.Rows[i], dicts, tableName), null);

                #endregion
            }

        }

        /// <summary>
        /// Creates the sheet SQL.
        /// </summary>
        /// <param name="dt">The dt.</param>
        /// <param name="dicts">The dicts.</param>
        /// <param name="tableName">Name of the table.</param>
        /// <returns></returns>
        public static string CreateSheetSQL(DataTable dt, Dictionary<string, string> dicts, string tableName)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("CREATE TABLE ");
            sb.Append("[" + tableName + "] ( ");
            foreach (var dict in dicts)
            {
                string datatype;
                switch (dt.Columns[dict.Key].DataType.Name.ToLower())
                {
                    case "float":
                        datatype = "float";
                        break;
                    case "int32":
                        datatype = "int";
                        break;
                    case "double":
                        datatype = "double";
                        break;
                    case "decimal":
                        datatype = "float";
                        break;
                    default:
                        datatype = "text";
                        break;
                }
                sb.Append(string.Format("[{0}] {1},", dict.Value, datatype));
            }
            sb.Remove(sb.Length - 1, 1).Append(")");
            return sb.ToString();
        }

        /// <summary>
        /// Inserts the data SQL.
        /// </summary>
        /// <param name="dr">The dr.</param>
        /// <param name="dicts">The dicts.</param>
        /// <param name="tableName">Name of the table.</param>
        /// <returns></returns>
        public static string InsertDataSQL(DataRow dr, Dictionary<string, string> dicts, string tableName)
        {
            StringBuilder fields = new StringBuilder();
            StringBuilder values = new StringBuilder();
            string strTemp;
            DateTime dateTime = DateTime.Now;
            string sqlInsert = "INSERT INTO {0} ({1}) values ({2}) ";

            foreach (var dict in dicts)
            {
                fields.Append("[").Append(dict.Value).Append("]").Append(",");
                strTemp = dr[dict.Key].ToString();
                if (DateTime.TryParse(strTemp, out dateTime))
                {
                    values.Append("'").Append(dateTime.ToString("yyyy-MM-dd HH:mm:ss")).Append("'").Append(",");
                }
                else
                {
                    values.Append("'").Append(strTemp).Append("'").Append(",");
                }
            }
            fields.Remove(fields.Length - 1, 1);
            values.Remove(values.Length - 1, 1);
            return String.Format(sqlInsert, tableName, fields.ToString(), values.ToString());
        }


        public static DataTable ExcelToDataTable(string connectionString, string sheetName)
        {
            DataTable dt = new DataTable();
            OleDbHelper oledbHelper = new OleDbHelper(connectionString);
            string ss = "select * from [" + sheetName + "]";
            dt = oledbHelper.ExecuteDataAdapter(CommandType.Text, ss, null).Tables[0];

            return dt;
        }


    }
}
